package com.chat.controller.campus;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/campus/chat")
public class ImageController {

    @Value("${ying_yan.chat_picture}")
    private String path;


    /**
     * 获取帖子的图片信息
     * @param fileName 图片名称
     * @return
     */
    @GetMapping(value = "/{fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<byte[]> getAvatar(@PathVariable String fileName) {
        try {
            //相对路径
            String avatarPath = path+ File.separator + fileName;

            // 将相对路径转换为绝对路径
            Path path = Paths.get(avatarPath);
            Resource resource = new FileSystemResource(path.toFile());

            if (resource.exists() && resource.isReadable()) {
                // 读取文件内容到字节数组
                byte[] avatarBytes = Files.readAllBytes(path);

                // 返回包含图片字节数据的ResponseEntity
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(avatarBytes);
            } else {
                // 如果没有找到头像或者不可读，返回404 Not Found
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            // 处理文件读取异常，返回500 Internal Server Error或其他状态码
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
